import React from 'react';
import PropTypes from 'prop-types';
import { removeToken } from '../../../../uitl/auth'
import { makeStyles } from '@material-ui/core/styles';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TablePagination from '@material-ui/core/TablePagination';
import TableRow from '@material-ui/core/TableRow';
import TableSortLabel from '@material-ui/core/TableSortLabel';
import { createBrowserHistory } from "history";
import Paper from '@material-ui/core/Paper';
import Checkbox from '@material-ui/core/Checkbox';
import { Delete, BorderColor } from '@material-ui/icons';
import { Button } from '@material-ui/core'

import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogContentText from '@material-ui/core/DialogContentText';
import DialogTitle from '@material-ui/core/DialogTitle';
import Snackbar from '@material-ui/core/Snackbar';

import PubSub from 'pubsub-js'
import { delPost, listPost } from '../../../../api/system/post'

function descendingComparator(a, b, orderBy) {
    if (b[orderBy] < a[orderBy]) {
        return -1;
    }
    if (b[orderBy] > a[orderBy]) {
        return 1;
    }
    return 0;
}

function getComparator(order, orderBy) {
    return order === 'desc'
        ? (a, b) => descendingComparator(a, b, orderBy)
        : (a, b) => -descendingComparator(a, b, orderBy);
}

function stableSort(array, comparator) {
    const stabilizedThis = array.map((el, index) => [el, index]);
    stabilizedThis.sort((a, b) => {
        const order = comparator(a[0], b[0]);
        if (order !== 0) return order;
        return a[1] - b[1];
    });
    return stabilizedThis.map((el) => el[0]);
}

const headCells = [
    { id: 'postId', numeric: false, disablePadding: true, label: '岗位编号' },
    { id: 'postCode', numeric: true, disablePadding: false, label: '岗位编码' },
    { id: 'postName', numeric: true, disablePadding: false, label: '岗位名称' },
    { id: 'postSort', numeric: true, disablePadding: false, label: '岗位排序' },
    { id: 'status', numeric: true, disablePadding: false, label: '状态' },
    { id: 'createTime', numeric: true, disablePadding: false, label: '创建时间' },
];

function EnhancedTableHead(props) {
    const { classes, onSelectAllClick, order, orderBy, numSelected, rowCount, onRequestSort } = props;  //numSelected 是选择多少
    const createSortHandler = (property) => (event) => {
        onRequestSort(event, property);
    };

    return (
        <TableHead style={{ backgroundColor: '#f8f8f9' }}>
            <TableRow>
                <TableCell padding="checkbox">
                    <Checkbox
                        indeterminate={numSelected > 0 && numSelected < rowCount}
                        checked={rowCount > 0 && numSelected === rowCount}
                        onChange={onSelectAllClick}
                        inputProps={{ 'aria-label': 'select all desserts' }}
                    />
                </TableCell>
                {headCells.map((headCell) => (
                    <TableCell
                        key={headCell.id}
                        align={headCell.numeric ? 'center' : 'left'}
                        padding={headCell.disablePadding ? 'none' : 'normal'}
                        sortDirection={orderBy === headCell.id ? order : false}
                    >
                        <TableSortLabel
                            active={orderBy === headCell.id}
                            direction={orderBy === headCell.id ? order : 'asc'}
                            onClick={createSortHandler(headCell.id)}
                        >
                            {headCell.label}
                            {orderBy === headCell.id ? (
                                <span className={classes.visuallyHidden}>
                                    {order === 'desc' ? 'sorted descending' : 'sorted ascending'}
                                </span>
                            ) : null}
                        </TableSortLabel>
                    </TableCell>
                ))}
                <TableCell align="center">
                    操作
                </TableCell>
            </TableRow>

        </TableHead>
    );
}

EnhancedTableHead.propTypes = {
    classes: PropTypes.object.isRequired,
    numSelected: PropTypes.number.isRequired,
    onRequestSort: PropTypes.func.isRequired,
    onSelectAllClick: PropTypes.func.isRequired,
    order: PropTypes.oneOf(['asc', 'desc']).isRequired,
    orderBy: PropTypes.string.isRequired,
    rowCount: PropTypes.number.isRequired,
};



const useStyles = makeStyles((theme) => ({
    root: {
        width: '100%',
    },
    paper: {
        width: '100%',
        marginBottom: theme.spacing(2),
    },
    table: {
        minWidth: 750,
    },
    visuallyHidden: {
        border: 0,
        clip: 'rect(0 0 0 0)',
        height: 1,
        margin: -1,
        overflow: 'hidden',
        padding: 0,
        position: 'absolute',
        top: 20,
        width: 1,
    },
}));
export default function EnhancedTable() {
    const classes = useStyles();
    const [order, setOrder] = React.useState('asc');
    const [orderBy, setOrderBy] = React.useState('postId');
    const [selected, setSelected] = React.useState([]);  //id 数据
    const [page, setPage] = React.useState(0);
    const [rowsPerPage, setRowsPerPage] = React.useState(5);
    const [rows, setRows] = React.useState([]);
    const [xianshidetiaojian,setxianshidetiaojian] =React.useState([]);
    const [shuxin, setshuxin] = React.useState(0);
    React.useEffect(() => {
        setSelected([])
        listPost(xianshidetiaojian).then(
            response => {
                console.log('成功了', response)
                setRows(response.rows)
                setshuxin(0)
            },
            error => {
                console.log("失败了", error)
                removeToken()
                let history = createBrowserHistory();
                history.push({
                    pathname: "/login",
                });
                history.go();
            }
        );
    }, [shuxin])
    const sx = PubSub.subscribe('ShuXin', (_, aaa) => {
        setshuxin(aaa)
    }) 
    const tiaojian = PubSub.subscribe('TiaoJian', (_, tiaojian) => {
        setxianshidetiaojian(tiaojian)
    })
    React.useEffect(() => {
        PubSub.publish('PengYe', { selected })
    }, [selected])
    const handleRequestSort = (event, property) => {
        const isAsc = orderBy === property && order === 'asc';
        setOrder(isAsc ? 'desc' : 'asc');
        setOrderBy(property);
    };
    const handleSelectAllClick = (event) => {
        if (event.target.checked) {
            const newSelecteds = rows.map((n) => n.postId);
            setSelected(newSelecteds);
            return;
        }
        setSelected([]);
    };
    //数据的多选参数
    const handleClick = (event, postId) => {
        const selectedIndex = selected.indexOf(postId);
        let newSelected = [];
        if (selectedIndex === -1) {
            newSelected = newSelected.concat(selected, postId);
        } else if (selectedIndex === 0) {
            newSelected = newSelected.concat(selected.slice(1));
        } else if (selectedIndex === selected.length - 1) {
            newSelected = newSelected.concat(selected.slice(0, -1));
        } else if (selectedIndex > 0) {
            newSelected = newSelected.concat(
                selected.slice(0, selectedIndex),
                selected.slice(selectedIndex + 1),
            );
        }
        setSelected(newSelected);
    };

    const handleChangePage = (event, newPage) => {
        setPage(newPage);
    };
    const handleChangeRowsPerPage = (event) => {
        setRowsPerPage(parseInt(event.target.value, 10));
        setPage(0);
    };
    const isSelected = (postId) => selected.indexOf(postId) !== -1;
    const emptyRows = rowsPerPage - Math.min(rowsPerPage, rows.length - page * rowsPerPage);
    //  警告框
    const [open, setOpen] = React.useState(false);
    const [post_id,setPoset_id] =React.useState(); //删除的id
    const [post_name,setPost_name] =React.useState(); //删除的post_name

    //  弹出消息框
    const [xiaoxitan, setxiaoxitan] = React.useState(false);

    const handleClickOpen = (event, postId, postName) => {

        setPoset_id(postId);
        setPost_name(postName);      
        setOpen(true);
    };

    const handleClose = () => {
        setOpen(false);
    };
    const handleDelete = (event, postId, postName) => {
        
        delPost(postId).then(
            response => {
                setOpen(false);
                setxiaoxitan(true);
                console.log('成功了', response);
                setshuxin(shuxin + 1);
                setInterval(()=>{
                    setxiaoxitan(false);
                },3000)

            },
            error => {
                window.alert("删除失败！")
                console.log("失败了", error)

            }
        )
    };
    return (
        <div className={classes.root}>

            <Paper className={classes.paper}>
                <TableContainer>
                    <Table
                        className={classes.table}
                        aria-labelledby="tableTitle"
                        size="medium"
                        aria-label="enhanced table"
                    >
                        <EnhancedTableHead
                            classes={classes}
                            numSelected={selected.length}
                            order={order}
                            orderBy={orderBy}
                            onSelectAllClick={handleSelectAllClick}
                            onRequestSort={handleRequestSort}
                            rowCount={rows.length}
                        />
                        <TableBody>
                            {stableSort(rows, getComparator(order, orderBy))
                                .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
                                .map((row, index) => {
                                    const isItemSelected = isSelected(row.postId);
                                    const labelId = `enhanced-table-checkbox-${index}`;

                                    return (
                                        <TableRow
                                            hover

                                            role="checkbox"
                                            aria-checked={isItemSelected}
                                            tabIndex={-1}
                                            key={row.postId}
                                            selected={isItemSelected}
                                        >
                                            <TableCell padding="checkbox" onClick={(event) => handleClick(event, row.postId)}>
                                                <Checkbox
                                                    checked={isItemSelected}
                                                    inputProps={{ 'aria-labelledby': labelId }}
                                                />
                                            </TableCell>
                                            <TableCell component="th" id={labelId} scope="row" padding="none" onClick={(event) => handleClick(event, row.postId)}>
                                                {row.postId}
                                            </TableCell>
                                            <TableCell align="center" onClick={(event) => handleClick(event, row.postId)}>{row.postCode}</TableCell>
                                            <TableCell align="center" onClick={(event) => handleClick(event, row.postId)}>{row.postName}</TableCell>
                                            <TableCell align="center" onClick={(event) => handleClick(event, row.postId)}>{row.postSort}</TableCell>
                                            <TableCell align="center" onClick={(event) => handleClick(event, row.postId)}>{row.status == 0 ? '正常' : '停用'}</TableCell>
                                            <TableCell align="center" onClick={(event) => handleClick(event, row.postId)}>{row.createTime}</TableCell>
                                            <TableCell align="center" >
                                                <Button color="primary" onClick={()=>PubSub.publish('ShujuxiugaideId', row.postId)} >
                                                    <BorderColor />修改
                                                </Button>
                                                <Button color="primary" onClick={(event) => handleClickOpen(event, row.postId, row.postName)}>
                                                    <Delete />删除
                                                </Button>
                                                
                                                <Dialog
                                                    open={open}
                                                    onClose={handleClose}
                                                    aria-labelledby="alert-dialog-title"
                                                    aria-describedby="alert-dialog-description"
                                                >
                                                    <DialogTitle id="alert-dialog-title" >删除数据 {post_id}</DialogTitle>
                                                    <DialogContent>
                                                        <DialogContentText id="alert-dialog-description">
                                                            确定删除编号：{post_id} , 岗位: {post_name}  这条记录吗?
                                                            请不要瞎搞！！！！！
                                                        </DialogContentText>
                                                    </DialogContent>
                                                    <DialogActions>
                                                        <Button onClick={handleClose} color="primary">
                                                            取消
                                                        </Button>
                                                        <Button onClick={(event) => handleDelete(event, post_id, post_name)} color="primary" autoFocus>
                                                            同意
                                                        </Button>
                                                    </DialogActions>
                                                </Dialog>
                                                <Snackbar
                                                    anchorOrigin={{ vertical: 'top', horizontal: 'center', }}
                                                    open={xiaoxitan}
                                                    message="删除成功"
                                                    key={shuxin}
                                                />
    
                                            </TableCell>
                                        </TableRow>
                                    );
                                })}
                            {emptyRows > 0 && (
                                <TableRow style={{ height: 53 * emptyRows }}>
                                    <TableCell colSpan={8} />
                                </TableRow>
                            )}
                        </TableBody>
                    </Table>
                </TableContainer>
                <TablePagination
                    rowsPerPageOptions={[5, 10, 25]}
                    component="div"
                    count={rows.length}
                    rowsPerPage={rowsPerPage}
                    labelRowsPerPage={"每页行数"}
                    page={page}
                    onPageChange={handleChangePage}
                    onRowsPerPageChange={handleChangeRowsPerPage}
                />
            </Paper>

        </div>
    );
}
